package com.android.music.prolyric.search;

import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.android.music.prolyric.database.DatabaseManger;

import android.util.Log;

public class SearchLyricsNew 
{
	private static final String xpath_en = "//*[@id='Songs']/div/div[5]/div[2]/div/div[3]";
	private static final String xpath_vn = "//*[@id='Songs']/div/div[5]/div[3]/div/div[3]";
	private static final   String loginUrl = "http://loidich.com/index.php?do=login&act=sm";
	static InputStream is = null;
	static JSONObject jObj = null;
	static String json = "";
	
	
	
	/*---------------------------Tim va nghe online---------------------------------------*/
	public ArrayList<HashMap<String, String>> getAllData(String songName) throws Exception
	{
		ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String,String>>();
		
		String[] linkSongs = getLinkSong(songName);
		
		DataHandler saxParser = new DataHandler();		
		
		if(linkSongs!=null)
		{			
			int n = linkSongs.length;	
			Log.i("n=", n+"");
			int k=1;
			for(int i=0;i<n;i++)
			{
				//Log.i("url link", linkSongs[i]);
				String checkNull = getNameSongSinger(linkSongs[i]);
				if(checkNull!=null)
				{
					HashMap<String, String> hashMap= new HashMap<String, String>();
		    		
		    		String s = getMp3Xml(linkSongs[i]);
		    		if(!s.equalsIgnoreCase("error"))
		    		{
		    			String[] str = saxParser.getData(s);
		    			if(str!=null)
		    			{
				    		hashMap.put("id",k+"");	
				    		hashMap.put("title", str[0]);
				    		hashMap.put("singer", str[1]);
				    		hashMap.put("source", str[2]);
				    		hashMap.put("url", linkSongs[i]);
				    		Log.i("id", k +"");
				    		Log.i("title", hashMap.get("title"));
				    		Log.i("singer", hashMap.get("singer"));
				    		Log.i("source", hashMap.get("source"));
				    		data.add(hashMap);
				    		k++;
		    			}
		    		}
				}
	    		
			}
			return data;
			
		}
		
		return null;
		
	}
	public String[] getLinkSong(String songName) throws Exception 
	{    	
        String result[];
        
        String strHref = "a[href*=" + songName.replaceAll("[\\s ']", "").trim();
       
        String strSearch = "http://loidich.com/index.php?do=loidich&act=search&ie=UTF-8&cx=partner-pub-3450596953728249%3A5606820231&cof=FORID%3A10&q=" + songName.replaceAll("[']+", "%27").trim().replaceAll(" ", "+");
        Log.i("Search + href", strSearch + " " + strHref);
        
        Document document = Jsoup.connect(strSearch).get();

        Elements nodeBlogStats = document.select(strHref);
        int n = nodeBlogStats.size();
        Log.i("n1=", n+"");
        if(n>0)
        {
        	result = new String[n/2];//6, 0 2 4
        	int k=0;
        	if(songName.indexOf(" ")>0)
        		
        	{
        		for(int i=0;i<n;i+=2)
            		result[k++] = nodeBlogStats.get(i).attr("abs:href");        			
        	}
        	else
        	{				
        		for(int i=n-1;i>0;i-=2)
            		result[k++] = nodeBlogStats.get(i).attr("abs:href");        		
        	}        	
        	
        	Log.i("test1", "ok");
        	return result;
        }  
    

        return null;
	}
	
	/*--------------------Ket thuc tim va nghe online----------------------------------*/
	
	
	/*---------------------------Tim chinh xac song-singer-------------------------*/
	public ArrayList<String[]> getLyric(String songName,String singer) throws Exception
	{
			
		String[] linkSongs = getLinkSong(songName,singer);
		//neu getonlylyric va tim dc dung 1 bai/nhieu bai
		
		if(linkSongs!=null)
		{	
			int n = linkSongs.length;	
			Log.i("n=", n+"");
			DataHandler saxParser = new DataHandler();
			//neu chi tim loi dich va tim dc
			if(n==1)
				return getAllLyrics(linkSongs[0]);
				
			//tim dc nhieu bai hat tuong tu
			else if(n>1)
			{
				
				ArrayList<String[]> a = new ArrayList<String[]>();		
				
				for(int i=0;i<n;i++)
				{
					String s = getNameSongSinger(linkSongs[i]);
					
		    		if(s!=null)
		    			{
		    				String result[]=new String[2];
		    				result[0]=s;
		    				result[1] = linkSongs[i];
		    				a.add(result);		    				
		    			}		    		
				}
				
				if(a!=null && a.size()>0)
					return a;				
			}
			
		}
		
		return null;
		
	}
		
	
	public String[] getLinkSong(String songName,String singer) throws Exception 
	{    	
        String result[];
        String strHref = "a[href*=" + songName.replaceAll("[^\\w]+", "").trim();
        
        String strSearch = "http://loidich.com/index.php?do=loidich&act=search&ie=UTF-8&cx=partner-pub-3450596953728249%3A5606820231&cof=FORID%3A10&q=" + songName.replaceAll("[^\\w\\s]+", "%27").trim().replaceAll(" ", "+");
        
        Document document = Jsoup.connect(strSearch).get();

        Elements nodeBlogStats = document.select(strHref);
        int n = nodeBlogStats.size();
        //Log.i("n1=", n+"");
        if(n>0)
        {
        	result = new String[n/2];//6, 0 2 4
        	int k=0;
        	if(songName.indexOf(" ")>0)
        	{
        		for(int i=0;i<n;i+=2)
            		result[k++] = nodeBlogStats.get(i).attr("abs:href");        			
        	}
        	else
        	{				
        		for(int i=n-1;i>0;i-=2)
            		result[k++] = nodeBlogStats.get(i).attr("abs:href");        		
        	}        	
        	for(int i=0;i<n/2;i++)
        		Log.i(""+i, result[i]);
        	Log.i("so bai hat tim dc", "" +n/2);
        	int i;
        	String s,str=songName.replaceAll(" ", "").toLowerCase();
        	String s1,str1=null;
        	if(singer!=null)
        		str1=singer.replaceAll(" ", "").toLowerCase();//them cai nay thoi
        	Log.i("songName", str);
        	int count=0;
        	int[] check = new int[n/2];
        	for(i=0;i<n/2;i++)
        		{
        			s =result[i].substring(result[i].indexOf("-")+1,result[i].lastIndexOf("-")).toLowerCase();
        			s1=result[i].substring(result[i].lastIndexOf("-")+1,result[i].lastIndexOf(".")).toLowerCase();
        			Log.i("Singer", s1);
        			if(s.equalsIgnoreCase(str) && str1!=null && s1.equalsIgnoreCase(str1))
        				{
	        				String[] r = new String[1];
	                    	r[0] = result[i];
	            			return r;					
        				}
        				
        			else if(s.contains(str))
    					{
    						check[count] = i;//0 1;1 2
    						count++;//1 2        						
    					}
        		}
        		
        	if(count>0)
        		{
        			String[] r = new String[count];
            		for(i=0;i<count;i++)
            			r[i] = result[check[i]];
    				return r;
        		} 
        	
        	Log.i("test1", "ok");
        	return result;
        }  
    

        return null;
	}
	
	public  String getNameSongSinger(String url) 
	{
		String s = url.substring(url.indexOf("-")+1);
		if(s.startsWith("8&cx=") || s.startsWith("-act::search--ie"))
			return null;
		return s.replaceAll(".html", "").trim();
	}
	
	public String[] getSong_Singer(String url)
	{
		DataHandler saxParser = new DataHandler();	
		String s = getMp3Xml(url);
		if(!s.equalsIgnoreCase("error"))
		{
			String[] str = saxParser.getData(s);
			String[] result = new String[2];
			if(str!=null)
				System.arraycopy(str, 0, result, 0, 2);
			return result;
	    	
		}
		
		return null;
	}
	
	/*public String[] getAllLyric(String urlSong) 
	{
		
		try 
		{
			return getLyricFromXpath(urlSong);			
		} 
		catch (Exception e) 
		{
			return null;
		}		
	}*/
	
	public ArrayList<String[]> getAllLyrics(String urlSong) 
	{
		ArrayList<String[]> a = new ArrayList<String[]>();		
		String result[]=new String[4];
		try 
		{
			String[] s = getLyricFromXpath(urlSong);			
			String s1[] = getSong_Singer(urlSong);
			System.arraycopy(s, 0, result, 0, 2);
			System.arraycopy(s1, 0, result, 2, 2);
			for(String k: result)
				Log.i("r", k);
			a.add(result);
					
			return a;
		} 
		catch (Exception e) 
		{
			return null;
		}		
	}
	//phai login o cho nayuh
	public String[] getLyricFromXpath(String strurl) throws Exception {
		String[] stats= new String[2];
		
		
		List<NameValuePair> listparams  = new ArrayList<NameValuePair>();
		if(DatabaseManger.username.equals(""))
		{
			DatabaseManger.username = "lemaibk08";
			DatabaseManger.password = "vienlemai";
		}
    	listparams.add(new BasicNameValuePair("username",DatabaseManger.username));
    	listparams.add(new BasicNameValuePair("password",DatabaseManger.password));
		// cau hinh thuoc tinh cleaner
		HtmlCleaner htmlCleaner = new HtmlCleaner();
		/*CleanerProperties props = htmlCleaner.getProperties();
		props.setAllowHtmlInsideAttributes(false);
		props.setAllowMultiWordAttributes(true);
		props.setRecognizeUnicodeChars(true);
		props.setOmitComments(true);*/
		
		
		/*Login to web and go to url*/
		
		  DefaultHttpClient httpClient = new DefaultHttpClient();
          HttpPost httpPost = new HttpPost();
          httpPost.setURI(new URI(loginUrl));
          httpPost.setEntity(new UrlEncodedFormEntity(listparams));

          HttpResponse httpResponse = httpClient.execute(httpPost);
          httpPost.setURI(new URI(strurl));
          httpResponse = httpClient.execute(httpPost);
          HttpEntity httpEntity = httpResponse.getEntity();
          
          is = httpEntity.getContent();
         
		
		
		
		//khong dung url nua
		
		TagNode root = htmlCleaner.clean(is);
	
		//query xpath
		Object[] statsNode = root.evaluateXPath(xpath_en);
		Object[] startsNode2 = root.evaluateXPath(xpath_vn);
		if(statsNode.length>0) {
			//do chi co 1 nen chon cai dau tien
			TagNode resultNode = (TagNode)statsNode[0];
			stats[0] = resultNode.getText().toString().trim();
			
		}
		if(startsNode2.length >0)
		{
			TagNode resultNode = (TagNode)startsNode2[0];
			stats[1] = resultNode.getText().toString().trim();
		}
		
		 
        httpPost.setURI(new URI("http://loidich.com/index.php?do=login&act=out"));
        httpClient.execute(httpPost);
		
		return stats;
	}
	
	//lay link xml cua link nghe nhac
	public String getMp3Xml(String urlSong)
	{
		String strMp3XmlLink="";
		
		Document document=null;
		try 
		{
			document = Jsoup.connect(urlSong).get();
			Element nodeBlogStats = document.select("[src*=xmlURL]").first();
	        strMp3XmlLink = nodeBlogStats.absUrl("abs:src");
	        strMp3XmlLink = strMp3XmlLink.substring(strMp3XmlLink.indexOf("=")+1);
	        //Log.i("xmlLink", strMp3XmlLink);
	        return strMp3XmlLink;
		} 
		
		catch (IllegalArgumentException e) 
		{
			return "error";
		}
		catch (Exception e) 
		{
			//e.printStackTrace();
			return "error";
		} 
		
	}
}
